var configs = {
  env: {
    fileName: ".env",
    data: {
      "VUE_APP_TOKENKEY=": "ym-prod-userToken",
      "VUE_APP_USERKEY=": "ym-prod-userInfo",
      "VUE_APP_SPACEID=": "ym-prod-currentSpaceId",
      "VUE_APP_DOMAIN=": "yunmaolink.com",
      "NODE_ENV=": "production",
    },
  },
  development: {
    fileName: ".env.development",
    data: {
      "VUE_APP_TOKENKEY=": "ym-test-userToken",
      "VUE_APP_USERKEY=": "ym-test-userInfo",
      "VUE_APP_SPACEID=": "ym-test-currentSpaceId",
      "VUE_APP_DOMAIN=": "yunmaolink.com",
      "NODE_ENV=": "production",
    },
  },
  development_local: {
    fileName: ".env.development.local",
    data: {
      "VUE_APP_TOKENKEY=": "ym-test-userToken",
      "VUE_APP_USERKEY=": "ym-test-userInfo",
      "VUE_APP_SPACEID=": "ym-test-currentSpaceId",
      "VUE_APP_DOMAIN=": "localhost",
      "NODE_ENV=": "development",
    },
  },
  test: {
    fileName: ".env.test",
    data: {
      "VUE_APP_TOKENKEY=": "ym-test-userToken",
      "VUE_APP_USERKEY=": "ym-test-userInfo",
      "VUE_APP_SPACEID=": "ym-test-currentSpaceId",
      "VUE_APP_DOMAIN=": "yunmaolink.com",
      "NODE_ENV=": "production",
    },
  },
  uat: {
    fileName: ".env.uat",
    data: {
      "VUE_APP_TOKENKEY=": "ym-uat-userToken",
      "VUE_APP_USERKEY=": "ym-uat-userInfo",
      "VUE_APP_SPACEID=": "ym-uat-currentSpaceId",
      "VUE_APP_DOMAIN=": "yunmaolink.com",
      "NODE_ENV=": "production",
    },
  },
  pre: {
    fileName: ".env.pre",
    data: {
      "VUE_APP_TOKENKEY=": "ym-prod-userToken",
      "VUE_APP_USERKEY=": "ym-prod-userInfo",
      "VUE_APP_SPACEID=": "ym-prod-currentSpaceId",
      "VUE_APP_DOMAIN=": "yunmaolink.com",
      "NODE_ENV=": "production",
    },
  },
};

module.exports = (api, options) => {
  api.postProcessFiles((files) => {
    initConfig(files, configs);
  });

  api.extendPackage({
    devDependencies: {
      "js-cookie": "^2.2.1",
    },
  });
  api.render("./template");
};

function initConfig(files, data) {
  for (let key in data) {
    let node = data[key];
    const file = files[node.fileName];
    if (!file) {
      let text = "";
      for (let key2 in node.data) {
        text += `${key2}${node.data[key2]}\n`;
      }
      files[node.fileName] = text;
    } else {
      for (let key in node.data) {
        const file = files[node.fileName];
        if (file.indexOf(key) > -1) {
          let name = key + ".+?(\\s)";
          let regx = new RegExp(name, "g");
          files[node.fileName] = file.replace(
            regx,
            key + node.data[key] + "\n"
          );
        } else {
          files[node.fileName] = file + "\n" + key + node.data[key] + "\n";
        }
      }
    }
  }
}
